import { Breadcrumb, Button, Table, Space, Tabs, TableProps } from 'antd';
import React, { FC } from 'react';
import { FormPanel, type FormPanelObject, FormPanelBtnAlign, InputType, Utils } from 'lfun-bg-comp';
import { useNavigate } from 'react-router-dom';
import _ from 'lodash';
import { PageContainer } from '@/component/page-container';
import { GENDER } from '@/constant/basicOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import styles from './index.less';
import { NewTeachersSrv } from '@/service/teacher';
import utils, { getPathRoot, get_stoge_pz, set_stoge_pz } from '@/utils';
import { STAFFING_ARRANGEMENT } from '@/constant/teachOptions';
import { searchSchoolOptions } from '@/service/options';
import { APPROVAL_STATUS } from '@/constant';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import dayjs from 'dayjs';

const Groups: FC = () => {
  const navigate = useNavigate();
  const [value, setValue] = React.useState();
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState<any>();
  const [tab, setTab] = React.useState<string>('1');
  const [loading, setLoading] = React.useState(false);
  const isSchool = Utils.getProps('isSchool');

  const init = async (parms: any, pageIndex, pageSize) => {
    //utils.showLoading();
    setLoading(true);
    try {
      const { success, data } =
        tab === '1'
          ? await NewTeachersSrv.listLaunch({ ...parms, page: pageIndex, per_page: pageSize })
          : await NewTeachersSrv.listApproval({ ...parms, page: pageIndex, per_page: pageSize });
      if (success) {
        setValue(data.items);
        setTotal(data.total);
        setPageSize(pageSize);
        setPageIndex(pageIndex);
      }
      //utils.hideLoaing(success);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
    setLoading(false);
  };

  React.useEffect(() => {
    init({}, 1, 10);
  }, []);

  const handleView = record => {
    navigate(`${getPathRoot()}/onboarding/approve/details/${record.teacher_id}`, { state: { ...record } });
  };
  const handleAgainSubmit = record => {
    navigate(`${getPathRoot()}/onboarding/edit/${record.teacher_id}`, { state: { ...record } });
  };

  const handleAudit = record => {
    navigate(`${getPathRoot()}/onboarding/approve/audit/${record.teacher_id}`, { state: { ...record } });
  };

  const columns: TableProps['columns'] = [
    {
      title: '姓名',
      dataIndex: 'teacher_name',
      key: 'teacher_name',
    },
    {
      title: '身份证号',
      dataIndex: 'teacher_id_number',
      key: 'teacher_id_number',
    },
    {
      title: '性别',
      dataIndex: 'teacher_gender',
      key: 'teacher_gender',
      render: (text: any) => {
        return _.find(GENDER, { value: String(text) })?.label;
      },
    },
    {
      title: '任职单位',
      dataIndex: 'school_name',
      key: 'school_name',
    },
    {
      title: '状态',
      dataIndex: 'approval_status',
      key: 'approval_status',
      render: (text, record) => {
        if (text) return _.find(APPROVAL_STATUS, { value: String(text) })?.label;
        return text;
      },
    },
    {
      title: '用人形式',
      dataIndex: 'employment_form',
      key: 'employment_form',
      render: (text: any) => {
        return _.find(STAFFING_ARRANGEMENT, { value: String(text) })?.label;
      },
    },
    // todo
    {
      title: '申请人',
      dataIndex: 'applicant_name',
      key: 'applicant_name',
    },
    // todo
    {
      title: '审批人',
      dataIndex: 'approval_name',
      key: 'approval_name',
    },
    // todo
    {
      title: '申请时间',
      dataIndex: 'start_time',
      key: 'start_time',
      render: (text: any) => {
        if (!text) return '';
        return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    // todo
    {
      title: '审批时间',
      dataIndex: 'approval_time',
      key: 'approval_time',
      render: (text: any) => {
        if (!text) return '';
        return dayjs(text).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      key: 'actions',
      //width: 280,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space size="small">
          <PermissionButton permission="view">
            <Button type="link" onClick={() => handleView(record)}>
              查看
            </Button>
          </PermissionButton>
          {['pending', 'progressing'].includes(record.approval_status) && (
            <PermissionButton permission="approval">
              <Button type="link" onClick={() => handleAudit(record)}>
                审批
              </Button>
            </PermissionButton>
          )}
          {['revoked'].includes(record.approval_status) && (
            <PermissionButton permission="edit">
              <Button type="link" onClick={() => handleAgainSubmit(record)}>
                再次提交
              </Button>
            </PermissionButton>
          )}
        </Space>
      ),
    },
  ];

  const searchTemplate = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '姓名',
          name: 'teacher_name',
          key: 'teacher_name',
        },
        {
          label: '所属机构',
          name: 'teacher_employer',
          key: 'teacher_employer',
          inputType: InputType.search, //'children',
          renderOption: searchSchoolOptions,
          formatSubmitValue: val => {
            if (typeof val === 'object') {
              return val.value;
            }
            return val;
          },
        },
        {
          label: '性别',
          name: 'teacher_gender',
          key: 'teacher_gender',
          inputType: 'select',
          inputProps: {
            placeholder: '请选择性别',
          },
          renderOption: GENDER,
        },
        // ?
        {
          label: '申请人',
          name: 'applicant_name',
          key: 'applicant_name',
        },
        // ?
        {
          label: '审批人',
          name: 'approval_name',
          key: 'approval_name',
        },
        {
          label: '身份证件号',
          name: 'teacher_id_number',
          key: 'teacher_id_number',
          inputType: 'text',
          textRange: [0, 18],
        },
      ],
    },
  ];

  return (
    <PageContainer header={<Breadcrumb items={[{ title: '新教职工审批' }]} />}>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        onLoad={(fromPanelObject: FormPanelObject) => {
          setForm(fromPanelObject);
        }}
        template={searchTemplate}
        onFinish={(fromPanelObject: FormPanelObject) => {
          init(fromPanelObject.getFieldsValue(), 1, 10);
        }}
      />
      <Tabs
        className={styles.tabs}
        type="card"
        onChange={(key: string) => {
          setTab(key);
          init(form.getFieldsValue(), 1, pageSize);
        }}
        items={[
          isSchool
            ? {
                label: '我发起',
                key: '1',
              }
            : {
                label: '我审批',
                key: '2',
              },
        ]}
      />
      <Table
        dataSource={value}
        columns={columns}
        scroll={{ x: 'max-content' }}
        loading={loading}
        pagination={{
          ...PAGINATIONCONFIG,
          total,
          pageSize,
          current: pageIndex,
          onChange: (pageIndex, pageSize) => {
            set_stoge_pz(pageSize);
            init(form.getFieldsValue(), pageIndex, pageSize);
          },
        }}
      />
    </PageContainer>
  );
};

export default Groups;
